#include "bwtC.h"
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#include <cstring> 



using namespace std;

unsigned int tamBloque = 0;

int stringComp(const void* dato1, const void* dato2){
    
    unsigned char* s1 = *(unsigned char**) dato1;
    unsigned char* s2 = *(unsigned char**) dato2;
    int offset1 = 0;
    int offset2 = 0;
    extern unsigned char buffer[];
    extern unsigned int tamBloque;
    
    
    for (unsigned int i=0 ; i < tamBloque ; i++){
        
        if (s1[0] > s2[0]) return 1;
        else if (s1[0] < s2[0]) return -1;
        
        if (s1[0] == s2[0]){
            offset1 = ( s1 - buffer + 1 ) % tamBloque ;
            s1 = (buffer + offset1);
            offset2 = ( s2 - buffer + 1 ) % tamBloque ;
            s2 = (buffer + offset2);
            
        }
        
    }
    
    return 0;
}


int bwt_algoritmoC(unsigned char* S,unsigned int N,unsigned char* L, unsigned int& I){
    
    //cout << "bwtC - a ordenar S:  " << S  << endl;
    extern unsigned int tamBloque;
    tamBloque = N;
   
    unsigned char ** m;
    m = new unsigned char *[N];

    unsigned int i;
    for ( i=0; i<N;i++){
        m[i] = &S[i];
    }

//    cout << "bwtC - antes q sort tengo m[0]:  " << m[0]  << endl;
//    cout << "bwtC - antes q sort tengo m[1]:  " << m[1]  << endl;
//    cout << "bwtC - antes q sort tengo m[2]:  " << m[2]  << endl;
//    cout << "bwtC - antes q sort tengo m[3]:  " << m[3]  << endl;
//    cout << "bwtC - antes q sort tengo m[4]:  " << m[4]  << endl;
//    cout << "bwtC - antes q sort tengo m[5]:  " << m[5]  << endl;
    
    qsort( m, N, sizeof(unsigned char*), stringComp);
    
//    cout << "bwtC - despues qsort tengo m[0]:  " << m[0]  << endl;
//    cout << "bwtC - despues qsort tengo m[1]:  " << m[1]  << endl;
//    cout << "bwtC - despues qsort tengo m[2]:  " << m[2]  << endl;
//    cout << "bwtC - despues qsort tengo m[3]:  " << m[3]  << endl;
//    cout << "bwtC - despues qsort tengo m[4]:  " << m[4]  << endl;
//    cout << "bwtC - despues qsort tengo m[5]:  " << m[5]  << endl;
    
    for ( i=0 ; i < N ; i++){
        
        if (m[i] != S ) L[i] = *(m[i] - 1);
        else {
            L[i] = *(m[i] + N - 1);
             
            I = i;
        }
    }
    
    delete[] m;

    return 0;
}

